Python 字串操作入門:基本存取與切片技巧 🔤
在 Python 中,字串(String)是最常用且功能強大的資料類型之一!
本篇將帶你掌握 字串建立、字元存取 與 切片操作 的基礎技能。
📌 字串的建立與存取基礎
- 使用單引號或雙引號(
''
或""
)建立字串,例如:"Hello"
或'Python'
- 透過
str()
函數可將其他資料類型轉換成字串 - 使用方括號
[]
搭配索引值來存取字串中的個別字元 - 索引從
0
開始(第一個字元) - 支援負數索引(
-1
表示最後一個字元)
字串存取範例程式碼
# 建立字串
my_string = "Hello, Python!"
# 訪問字串中的字元
print(my_string[0]) # H(索引0對應第一個字元)
print(my_string[-1]) # !(索引-1對應最後一個字元)
print(my_string[-2]) # n(索引-2對應倒數第二個字元)
# 使用 str() 將數字轉換成字串
number = 123
number_str = str(number) # 將整數number轉換成字串number_str
print(number_str) # 123
📌 字串切片技巧 (String Slicing)
- 使用
[start:end:step]
語法來擷取子字串: - start:起始索引,預設為
0
- end:結束索引(不包含此索引位置),預設為字串長度
- step:步進值,預設為
1
,可使用負值進行反向切片 - 省略參數的靈活運用能快速提取字串片段
字串切片範例程式碼
# 原始字串
my_string = "Hello, Python!"
# 使用切片提取子字串
print(my_string[0:5]) # Hello(索引 0 到 4;不包含end 5)
print(my_string[7:]) # Python!(從索引 7 開始到結尾)
print(my_string[:5]) # Hello(從開頭到索引 4;不包含end 5)
print(my_string[::2]) # Hlo yhn(提取整個字串,每隔一個字符取一次)
print(my_string[::-1]) # !nohtyP ,olleH(反向切片)
💡 Python 字串操作小技巧
- 索引靈活性:善用索引和切片可快速操作字串內容
- 負索引優勢:利用負索引方便處理字串尾部的字元
- 切片特性:結束索引處的字元不會被包含在切片結果中
- 不可變性:切片操作不會修改原始字串,而是建立全新的字串物件
- 效能考量:切片操作在處理大型文本時比逐字元操作更高效
相關標籤 (Tags) 🏷️
#Python #PythonStrings #StringManipulation #字串處理 #PythonTutorial #StringSlicing #PythonProgramming #LearnPython #StringOperations #PythonTips #字串切片 #PythonIndexing #StringBasics #PythonForBeginners #字元存取